<template>
  <p-modal
    v-model="visible"
    :title="title"
    :width="1000"
    :footer="isEdit ? undefined : null"
    :get-container="getContainer"
    :mask-closable="false"
    :dialog-style="{ top: '40px' }"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="content-container">
      <p-form-model
        v-if="isEdit"
        class="searh-form"
        :model="form"
        :rules="rules"
        layout="inline"
      >
        <p-form-model-item label="销售组">
          <p-input :value="form.salesGroupName" disabled placeholder="请输入" />
        </p-form-model-item>
        <p-form-model-item label="客户简称">
          <p-input :value="form.customerName" disabled placeholder="请输入" />
        </p-form-model-item>
        <p-form-model-item label="Model Name">
          <p-input :value="form.modelName" disabled placeholder="请输入" />
        </p-form-model-item>
      </p-form-model>
      <p-table
        class="table-list-container"
        row-key="id"
        :columns="columns"
        bordered
        :scroll="{ x: '100%', y: 300 }"
        :data-source="formatDataSource"
        :pagination="false"
        :row-selection="isEdit && rowSelectionMixin"
        @change="handleTableChange"
      />
    </div>
  </p-modal>
</template>

<script>
import { getBpRelationList } from '@/api/forecast';
import mixinTable from '@/mixins/mixin-table.js';
import { createMonthArray } from '@/utils/time';
import Decimal from 'decimal.js';

export default {
  mixins: [mixinTable],
  props: {
    value: {
      type: [String, Number],
      default: undefined,
    },
    getContainer: {
      type: Function,
      default: () => document.body,
    },
    timeRange: {
      type: Array,
      default: () => ['2021-01', '2021-05'],
    },
    visible: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: true,
    },
    index: {
      type: Number,
      default: 0,
    },
    condition: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      parentId: '',
      orgGroupOptions: [],
    };
  },

  computed: {
    form() {
      return this.condition;
    },
    title() {
      return this.isEdit ? '选择BP关系ID' : 'BP关系ID';
    },
    dictOptions() {
      return this.$store.state.dictionary.dict || {};
    },
    formatDataSource() {
      if (!this.dataSource.length) return [];
      return this.dataSource.map((item) => {
        const price = JSON.parse(item.price || '{}');
        const quantity = JSON.parse(item.quantity || '{}');
        const selfPrice = this.ranges.reduce((pre, cur) => {
          const p = Number(price[cur]) || 0;
          const q = Number(quantity[cur]) || 0;
          pre[cur] = new Decimal(p)
            .mul(new Decimal(q))
            .div(100000000)
            .toFixed();
          return pre;
        }, {});

        const selfQuantity = this.ranges.reduce((pre, cur) => {
          const m = Number(item.modelCutRate) || 0;
          const q = Number(quantity[cur]) || 0;
          let result = Math.ceil(q / m) || 0;
          if (!Number.isFinite(result)) {
            result = 0;
          }
          pre[cur] = result;
          return pre;
        }, {});

        return {
          ...item,
          appearance: this.dictOptions['shape']?.[item.appearance],
          application: this.dictOptions['application']?.[item.application],
          manufactureArea:
            this.dictOptions['production_place']?.[item.manufactureArea],
          factoryCode: this.dictOptions['factory_code']?.[item.factoryCode],
          category: this.dictOptions['category']?.[item.category],
          price,
          quantity,
          selfPrice,
          selfQuantity,
        };
      });
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: 'BP编号',
          dataIndex: 'serialNumber',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: 'BP名称',
          width: 120,
          dataIndex: 'name',
          ellipsis: true,
        },
        {
          align: 'center',
          title: 'BP关系ID',
          dataIndex: 'relationId',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '销售组',
          dataIndex: 'salesGroupName',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '厂别',
          dataIndex: 'factoryCode',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerName',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '机种',
          dataIndex: 'modelInfoName',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: 'Model Name',
          dataIndex: 'modelName',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '料号',
          width: 150,
          dataIndex: 'materialCode',
          ellipsis: true,
        },
        {
          align: 'center',
          title: '生产地',
          dataIndex: 'manufactureArea',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          width: 120,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '模切比',
          width: 150,
          dataIndex: 'modelCutRate',
          ellipsis: true,
        },
        {
          align: 'center',
          title: '形态',
          width: 150,
          ellipsis: true,
          dataIndex: 'appearance',
        },
        {
          align: 'center',
          title: '客户项目',
          width: 150,
          ellipsis: true,
          dataIndex: 'item',
        },
        {
          align: 'center',
          title: '内部项目',
          width: 150,
          ellipsis: true,
          dataIndex: 'innerItem',
        },
        {
          align: 'center',
          title: '类别',
          width: 150,
          ellipsis: true,
          dataIndex: 'category',
        },
        {
          align: 'center',
          title: '备注',
          width: 150,
          ellipsis: true,
          dataIndex: 'remark',
        },
        {
          align: 'center',
          title: '数量（小片Kpcs）',
          dataIndex: 'quantity',
          children: this.createMonthColumns('quantity'),
        },
        {
          align: 'center',
          title: '单价（人民币：元）',
          dataIndex: 'price',
          children: this.createMonthColumns('price'),
        },
        {
          align: 'center',
          title: '营收（人民币：亿元）',
          dataIndex: 'selfPrice',
          children: this.createMonthColumns('selfPrice'),
        },
        {
          align: 'center',
          title: '数量（大板Ksht）',
          dataIndex: 'selfQuantity',
          children: this.createMonthColumns('selfQuantity'),
        },
      ];
      return columns;
    },
    ranges() {
      return createMonthArray(this.timeRange);
    },
  },
  watch: {
    visible: {
      handler(val) {
        val && this.getList();
      },
    },
  },
  created() {
    this.rowSelectionMixin.type = 'radio';
  },
  methods: {
    createMonthColumns(key) {
      const list = this.ranges.map((item) => {
        const dataIndex = `${key}.${item}`;
        return {
          align: 'center',
          title: item,
          width: 120,
          dataIndex,
        };
      });
      return list;
    },
    handleSearch() {
      this.paginationMixin.current = 1;
      this.getList();
    },

    async getList() {
      const result = await getBpRelationList([
        {
          ...this.condition,
          type: 1,
          customerName: undefined,
          salesGroupName: undefined,
          relationId:
            !this.isEdit && this.condition.relationId
              ? this.condition.relationId
              : undefined,
        },
      ]);
      const data = result?.data?.data || [];
      this.dataSource = data[0]?.planDetailList || [];
    },
    handleCancel() {
      this.rowSelectionMixin.selectedRowKeys = [];
      this.$emit('update:visible', false);
      this.$emit('cancel', false);
    },
    handleOk() {
      if (!this.isEdit) {
        this.handleCancel();
        return;
      }
      const keys = this.rowSelectionMixin.selectedRowKeys;
      if (!keys.length) {
        this.$message.error('请选择BP关系ID！');
        return;
      }
      const current = this.dataSource.find((item) => item.id === keys[0]);
      this.$emit('change', current.relationId);
      this.handleCancel();
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      // this.asc = sorter.order === 'ascend' ? true : false;
      // this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.rowSelectionMixin.selectedRowKeys = [];
      this.getList();
    },
  },
};
</script>

<style lang="less" scoped>
.content-container {
  .searh-form {
    box-sizing: border-box;
    background-color: #f7f7f8;
    padding: 10px;
    padding-bottom: 0px;
    margin-bottom: 20px;
    width: 100%;
    .poros-form-item {
      width: 28%;
      margin-bottom: 10px;
    }
    /deep/ .poros-form-item-label {
      width: 80px;
    }
    /deep/ .poros-form-item-control-wrapper {
      width: calc(100% - 80px);
    }
  }
}
</style>
